<template>
  <div class="marketing-coupon">
    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="优惠券名称">
          <el-input v-model="searchForm.name" placeholder="请输入优惠券名称" clearable />
        </el-form-item>
        <el-form-item label="优惠券类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option label="满减券" value="full_reduction" />
            <el-option label="折扣券" value="discount" />
            <el-option label="现金券" value="cash" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="未开始" value="not_started" />
            <el-option label="进行中" value="active" />
            <el-option label="已结束" value="ended" />
            <el-option label="已停用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建优惠券
        </el-button>
      </div>
    </div>

    <!-- 优惠券列表 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column prop="name" label="优惠券名称" min-width="150" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="discount" label="优惠额度" width="120">
          <template #default="{ row }">
            <span v-if="row.type === 'discount'">{{ row.discount }}折</span>
            <span v-else>¥{{ row.discount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="minAmount" label="最低消费" width="100">
          <template #default="{ row }">
            ¥{{ row.minAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="totalCount" label="发放数量" width="100" />
        <el-table-column prop="usedCount" label="使用数量" width="100" />
        <el-table-column prop="validPeriod" label="有效期" width="200">
          <template #default="{ row }">
            {{ row.startTime }} 至 {{ row.endTime }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleDistribute(row)">
              发放
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="handleToggleStatus(row)"
              :style="{ color: row.status === 'disabled' ? '#67C23A' : '#F56C6C' }"
            >
              {{ row.status === 'disabled' ? '启用' : '停用' }}
            </el-button>
            <el-popconfirm title="确定删除该优惠券吗？" @confirm="handleDelete(row)">
              <template #reference>
                <el-button type="text" size="small" style="color: #f56c6c;">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="getCouponData"
          @size-change="getCouponData"
        />
      </div>
    </el-card>

    <!-- 优惠券表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建优惠券' : '编辑优惠券'"
      width="800px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优惠券名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入优惠券名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优惠券类型" prop="type">
              <el-select v-model="formData.type" style="width: 100%;">
                <el-option label="满减券" value="full_reduction" />
                <el-option label="折扣券" value="discount" />
                <el-option label="现金券" value="cash" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优惠额度" prop="discount">
              <el-input-number 
                v-model="formData.discount" 
                :min="0" 
                :precision="formData.type === 'discount' ? 1 : 2"
                style="width: 100%;" 
              />
              <span style="margin-left: 10px;">
                {{ formData.type === 'discount' ? '折' : '元' }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最低消费" prop="minAmount">
              <el-input-number v-model="formData.minAmount" :min="0" :precision="2" style="width: 100%;" />
              <span style="margin-left: 10px;">元</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发放数量" prop="totalCount">
              <el-input-number v-model="formData.totalCount" :min="1" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每人限领" prop="limitPerUser">
              <el-input-number v-model="formData.limitPerUser" :min="1" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="有效期" prop="validPeriod">
          <el-date-picker
            v-model="formData.validPeriod"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="使用说明">
          <el-input v-model="formData.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 发放优惠券对话框 -->
    <el-dialog v-model="distributeDialogVisible" title="发放优惠券" width="600px">
      <el-form :model="distributeForm" label-width="100px">
        <el-form-item label="发放方式">
          <el-radio-group v-model="distributeForm.method">
            <el-radio label="all">全部用户</el-radio>
            <el-radio label="vip">VIP用户</el-radio>
            <el-radio label="new">新用户</el-radio>
            <el-radio label="custom">指定用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发放数量">
          <el-input-number v-model="distributeForm.count" :min="1" :max="1000" />
        </el-form-item>
        <el-form-item label="发放说明">
          <el-input v-model="distributeForm.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="distributeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmDistribute">
          确认发放
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { getCouponList, addCoupon, updateCoupon, deleteCoupon } from '@/api/marketing'

export default {
  name: 'MarketingCoupon',
  components: {
    Search, Refresh, Plus
  },
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const distributeDialogVisible = ref(false)
    const dialogType = ref('create')
    const formRef = ref()

    const searchForm = reactive({
      name: '',
      type: '',
      status: ''
    })

    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    const tableData = ref([])

    const formData = reactive({
      id: '',
      name: '',
      type: 'full_reduction',
      discount: 0,
      minAmount: 0,
      totalCount: 100,
      limitPerUser: 1,
      validPeriod: [],
      description: ''
    })

    const distributeForm = reactive({
      method: 'all',
      count: 50,
      remark: ''
    })

    const formRules = {
      name: [
        { required: true, message: '请输入优惠券名称', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择优惠券类型', trigger: 'change' }
      ],
      discount: [
        { required: true, message: '请输入优惠额度', trigger: 'blur' }
      ],
      totalCount: [
        { required: true, message: '请输入发放数量', trigger: 'blur' }
      ],
      validPeriod: [
        { required: true, message: '请选择有效期', trigger: 'change' }
      ]
    }

    const typeMap = {
      full_reduction: { text: '满减券', color: 'primary' },
      discount: { text: '折扣券', color: 'success' },
      cash: { text: '现金券', color: 'warning' }
    }

    const statusMap = {
      not_started: { text: '未开始', color: 'info' },
      active: { text: '进行中', color: 'success' },
      ended: { text: '已结束', color: 'info' },
      disabled: { text: '已停用', color: 'danger' }
    }

    const getTypeText = (type) => typeMap[type]?.text || type
    const getTypeColor = (type) => typeMap[type]?.color || 'default'
    const getStatusText = (status) => statusMap[status]?.text || status
    const getStatusColor = (status) => statusMap[status]?.color || 'default'

    const getCouponData = async () => {
      loading.value = true
      try {
        const res = await getCouponList({
          page: pagination.current,
          size: pagination.size,
          ...searchForm
        })
        
        if (res && (res.code === 200 || res.data || res.content)) {
          const data = res.data || res
          tableData.value = data.content || data.records || data || []
          pagination.total = data.totalElements || data.total || 0
        } else {
          tableData.value = []
          pagination.total = 0
        }
      } catch (error) {
        console.error('获取优惠券列表失败:', error)
        ElMessage.warning('获取优惠券列表失败，请检查网络连接')
        tableData.value = []
        pagination.total = 0
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      pagination.current = 1
      getCouponData()
    }

    const handleReset = () => {
      Object.assign(searchForm, {
        name: '',
        type: '',
        status: ''
      })
      handleSearch()
    }

    const handleCreate = () => {
      dialogType.value = 'create'
      resetFormData()
      dialogVisible.value = true
    }

    const handleEdit = (row) => {
      dialogType.value = 'edit'
      Object.assign(formData, {
        ...row,
        validPeriod: [row.startTime, row.endTime]
      })
      dialogVisible.value = true
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除该优惠券吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await deleteCoupon(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          getCouponData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const currentCoupon = ref(null)

    const handleDistribute = async (row) => {
      currentCoupon.value = row
      distributeDialogVisible.value = true
    }

    const handleToggleStatus = async (row) => {
      try {
        const newStatus = row.status === 'disabled' ? 'active' : 'disabled'
        const res = await updateCoupon(row.id, { status: newStatus })
        
        if (res.code === 200) {
          row.status = newStatus
          ElMessage.success(`${newStatus === 'active' ? '启用' : '停用'}成功`)
          getCouponData()
        }
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }

    const handleSubmit = async () => {
      try {
        await formRef.value.validate()
        
        let res
        if (dialogType.value === 'create') {
          res = await addCoupon(formData)
        } else {
          res = await updateCoupon(formData.id, formData)
        }
        
        if (res.code === 200) {
          ElMessage.success(dialogType.value === 'create' ? '创建成功' : '更新成功')
          dialogVisible.value = false
          getCouponData()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }

    const handleConfirmDistribute = async () => {
      try {
        const res = await updateCoupon(currentCoupon.value.id, {
          action: 'distribute',
          ...distributeForm
        })
        
        if (res.code === 200) {
          ElMessage.success('优惠券发放成功')
          distributeDialogVisible.value = false
          getCouponData()
        }
      } catch (error) {
        ElMessage.error('发放失败')
      }
    }

    const resetFormData = () => {
      Object.assign(formData, {
        id: '',
        name: '',
        type: 'full_reduction',
        discount: 0,
        minAmount: 0,
        totalCount: 100,
        limitPerUser: 1,
        validPeriod: [],
        description: ''
      })
    }

    onMounted(() => {
      getCouponData()
    })

    return {
      loading,
      submitLoading,
      dialogVisible,
      distributeDialogVisible,
      dialogType,
      formRef,
      searchForm,
      pagination,
      tableData,
      formData,
      distributeForm,
      formRules,
      getTypeText,
      getTypeColor,
      getStatusText,
      getStatusColor,
      getCouponData,
      handleSearch,
      handleReset,
      handleCreate,
      handleEdit,
      handleDelete,
      handleDistribute,
      handleToggleStatus,
      handleSubmit,
      handleConfirmDistribute
    }
  }
}
</script>

<style scoped>
.marketing-coupon {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 